package com.feihong.yw189.activity.yonghuzhongxin.userinfo;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.app.App;
import com.feihong.yw189.global.RequestTools;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.User.my.EditPhoneModel;
import com.feihong.yw189.utils.MessageEvent;
import com.feihong.yw189.utils.UserLoginInfo;
import org.greenrobot.eventbus.EventBus;
import org.xutils.common.Callback;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class UserInfoEditActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.rl_goback)
    RelativeLayout rlGoback;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.iv_confirm)
    TextView ivConfirm;
    @BindView(R.id.top_back_layout)
    LinearLayout topBackLayout;

    int type = 0; //页面类型
    private CountDownTimer timer; //验证码倒计时
    private TextView codeTimmer;
    private Callback.Cancelable cancelable;
    private String userPhone = "";
    private Unbinder unbinder;

    private Button tvOk;
    private TextView edYsmm;
    private TextView edXmm;
    private TextView edQrmm;
    private Button uPtvOk;
    private TextView tvForpwd;
    private Button payTvOk;
    private TextView payTvForpwd;
    private TextView editPhonenum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();

        if (intent != null) {
            type = intent.getIntExtra("type", 0);
        }

        switch (type) {
            case 0:
                setContentView(R.layout.activity_user_info_edit);
                break;
            case 1:
                setContentView(R.layout.my_setting_phone_edit);
                //计时器初始化
                codeTimmer = (TextView) findViewById(R.id.codeTimmer);
                break;
            case 2:
                setContentView(R.layout.my_setting_login_pwd);
                codeTimmer = (TextView) findViewById(R.id.codeTimmer);
                break;
            case 3:
                setContentView(R.layout.my_setting_pay_pwd);
                codeTimmer = (TextView) findViewById(R.id.codeTimmer);
                break;
            case 4:
                setContentView(R.layout.my_setting_fingerprint);
                break;
            case 5:
                setContentView(R.layout.my_setting_faceid);
                break;
            default:
                break;
        }
        unbinder = ButterKnife.bind(this);
        initView();
    }

    @Override
    public void setTheme() {

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @SuppressLint("WrongConstant")
    public void initView() {
        setBackButtonFinish();

        ivLin.setVisibility(View.GONE);

        switch (type) {
            case 0:
                setPageTitle("昵称修改");
//                ivLin.setVisibility(View.GONE);
                ivConfirm.setVisibility(View.VISIBLE);
//                editName();
                break;
            case 1:
                setPageTitle("更换手机号");
                //放入原手机号,不可点击
                editPhonenum = (TextView) findViewById(R.id.edit_phonenum);
                userPhone = UserLoginInfo.getUserLoginInfoInstance().getUserLoc().getUserMobile();
                editPhonenum.setText(userPhone);
                editPhonenum.setEnabled(false);

                //button
                tvOk = (Button) findViewById(R.id.tv_ok);
                tvOk.setOnClickListener(this);
                editPhone();
                break;
            case 2:
                setPageTitle("登录密码修改");
                uPtvOk = (Button) findViewById(R.id.u_ptv_ok);
                uPtvOk.setOnClickListener(this);
                editPhone();
                break;
            case 3:
                setPageTitle("支付密码修改");
                payTvOk = (Button) findViewById(R.id.pay_tv_ok);
                payTvOk.setOnClickListener(this);
                editPhone();
                break;
            case 4:
                setPageTitle("指纹设置");
                break;
            case 5:
                setPageTitle("面部ID修改");
                break;
            default:
                break;
        }
    }


//    private void editName() {
//        changeNickName = (EditText) findViewById(R.id.change_nick_name);
//        changeNickName.setText("店家联盟test");
//
//        ivConfirm.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                String nameStr = changeNickName.getText().toString().trim();
//
//                editNameMethod(nameStr);
//                finish();
//            }
//        });
//    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_ok:
                TextView codeStr = (TextView) findViewById(R.id.regionCode);
                //处理逻辑
                editPhoneMe("" + codeStr.getText());
                return;
            case R.id.u_ptv_ok:
                edXmm = (TextView) findViewById(R.id.ed_xmm);
                edQrmm = (TextView) findViewById(R.id.ed_qrmm);

                TextView codeTxt = (TextView) findViewById(R.id.regionCode);
                //处理逻辑
                editloginPwd(0, "" + edXmm.getText(), "" +edQrmm.getText(),""+ codeTxt.getText());
                break;
            case R.id.pay_tv_ok:
                edXmm = (TextView) findViewById(R.id.ed_xmm);
                edQrmm = (TextView) findViewById(R.id.ed_qrmm);

                TextView codeNum = (TextView) findViewById(R.id.regionCode);
                editloginPwd(1, ""+edXmm.getText(), ""+edQrmm.getText(), ""+ codeNum.getText());
                break;
            default:break;
        }
    }

    private void editloginPwd(int type, String pwd, String conforPwd, String code) {
        if(pwd.isEmpty()){
            showToast("新密码不能为空!");
            edXmm.setFocusable(true);
            edXmm.requestFocus();
        }else if(conforPwd.isEmpty()){
            showToast("确认密码不能为空!");
            edQrmm.setFocusable(true);
            edQrmm.requestFocus();
        }else if(pwd.length() < 6){
            showToast("密码长度至少6个字符!");
            edQrmm.setFocusable(true);
            edQrmm.requestFocus();
        }else if(! pwd.equals(conforPwd)){
            showToast("两次密码不一致!");
        }else if(code.isEmpty()){
            showToast("请输入验证码!");
        }else{
            Callback.Cancelable callBackPwd = null;
            switch (type){
                case 0://登录密码
                    callBackPwd =  App.getApp().getHttpTools().editPwd(pwd, code, pwdCallback);
                    break;
                case 1://支付密码
                    callBackPwd =  App.getApp().getHttpTools().editPayPwd(pwd, code, pwdCallback);
                    break;
            }
            RequestTools.addNewRequest(UserInfoEditActivity.class.getName(),callBackPwd);
        }
    }

    RequestCallBack<String> pwdCallback = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            try{
                EditPhoneModel model = JSONObject.parseObject(result, EditPhoneModel.class);
                if(model != null){
                    if(model.getStatus() ==1){
                        finish();
                        showToast(model.getInfo());
                    }else{
                        showToast(model.getInfo());
                    }
                }else{
                    showErrorToast("解析出错,请重试");
                }
            }catch (Exception ex){
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if(activityIsDestory()){return;}
            showToast(getResources().getString(R.string.connect_sever_error_toast));
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {

        }
    };

    private void editNameMethod(String nameStr) {
        UserLoginInfo.getUserLoginInfoInstance().setUserName("对方的身份");
        EventBus.getDefault().post(new MessageEvent(MessageEvent.EDIT_NAME));
    }


    private void editPhone() {
        if (timer != null) {
            timer.cancel();
            codeTimmer.setText("获取验证码");
            codeTimmer.setEnabled(true);
        }
    }

    @Override
    public void setBackButtonFinish() {
       if (iv_back != null) {
           iv_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }

    //点击获取验证码按钮
    public void getCode(View view) {

        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                codeTimmer.setText("倒计时:" + millisUntilFinished / 1000 + "S");
                codeTimmer.setEnabled(false);
            }

            @Override
            public void onFinish() {
                codeTimmer.setText("重新获取");
                codeTimmer.setEnabled(true);
            }
        }.start();

        //发送验证码
        cancelable = App.getApp().getHttpTools().sendCode(commonCallback);
        RequestTools.addNewRequest(UserInfoEditActivity.class.getName(),cancelable);
    }

    RequestCallBack commonCallback = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            EditPhoneModel model = JSONObject.parseObject(result, EditPhoneModel.class);
//            String token = model.getData().getToken();
//            if(token != null && !token.isEmpty()){
//                UserLoginInfo.updateUserToken(token);
//            }

            if(model.getStatus() == 1) {
            }else{
                timer.cancel();
                codeTimmer.setText("重新获取");
                codeTimmer.setEnabled(true);
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            //失败
            timer.cancel();
            codeTimmer.setText("重新获取");
            codeTimmer.setEnabled(true);
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
            //取消时，比如关闭Activity时，还在发送中，我们会取消当前的请求。。。

             if(cancelable!=null && cancelable.isCancelled())
             {
             cancelable.cancel();
             }
        }
        @Override
        public void onFinished() {
            //不管请求成功，失败，取消 都完成进入的方法
        }
    };

    //修改手机号码
    private void editPhoneMe(String code) {
        if(code.isEmpty()){
        }else {
            //进入修改密码页面
            Intent intent = new Intent(getApplication(), EditPhoneNumActivity.class);
            intent.putExtra("sms_no", code);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清空请求
        RequestTools.removeRequest(UserInfoEditActivity.class.getName());

        if (unbinder != null) {
            unbinder.unbind();
        }
    }
}
